package com.lyl.security.utils;

import com.lyl.common.exception.BizException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

/**
 * @author Mr.Luo
 * @date 2022-09-19 14:17
 * @desc jwt工具类
 */
@Component
public class JwtUtil {

    public static final String PRIVATE_KEY = "123456";

    /**
     * 创建token
     *
     * @param subject 主题
     * @return token
     */
    public static String createToken(String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY)
                .compact();
    }

    public static String parseToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(PRIVATE_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new BizException("token已过期");
        } catch (Exception e) {
            throw new BizException("token格式化异常");
        }
        return claims.getSubject();
    }
}
